package com.kanas.webak.config.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Singleton;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kanas.framework.business.BusinessException;
import com.kanas.webak.config.domain.I18nResource;
import com.kanas.webak.config.repository.I18nResourceRepository;

@Service("com.kanas.webak.config.service.i18nresourceservice")
@Singleton
public class I18nResourceServiceImpl  implements I18nResourceService{
	
	@Autowired
	private I18nResourceRepository i18nResourceRepository;
	
	@Override
	@Transactional
	public String addNew(I18nResource ir) throws Exception {
		I18nResource i18n = i18nResourceRepository.findOne(ir.getId());
		if(i18n!=null)throw BusinessException.DATA_DUPLICATION;
		i18nResourceRepository.save(ir);
		return ir.getId();
	}
	
	@Override
	@Transactional
	public String update(I18nResource ir) throws Exception {
		I18nResource i18n = i18nResourceRepository.findOne(ir.getOldId());
		if(i18n==null)throw BusinessException.DATA_NOT_FOUND;
		i18n.setLabel(ir.getLabel());
		i18n.setCode(ir.getCode());
		i18n.setLang(ir.getLang());
		i18n.setScope(ir.getScope());
		i18nResourceRepository.save(i18n);
		return ir.getOldId();
	}
	
	@Override
	@Transactional
	public I18nResource findOne(String id) {
		I18nResource dt = i18nResourceRepository.findOne(id);
		return dt;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	@Transactional
	public List<I18nResource> findAll() {
		Iterator<I18nResource> dts = i18nResourceRepository.findAll().iterator();
		return toList(dts);
	}
	
	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List toList(Iterator its) {
		List list = new ArrayList();
		while(its.hasNext()) {
			list.add(its.next());
		}
		return list;
	}

	public I18nResourceRepository getI18nResourceRepository() {
		return i18nResourceRepository;
	}

	public void setI18nResourceRepository(I18nResourceRepository i18nResourceRepository) {
		this.i18nResourceRepository = i18nResourceRepository;
	}
}
